package common
{

	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLStream;
	import flash.system.LoaderContext;
	import flash.utils.ByteArray;

	import net.message.BaseMessage;

	import util.Logger;

	public class HTTPService extends URLStream
	{

		private var _url:String;
		public var handler:Function;
		private var _request:URLRequest;

		public function HTTPService(host:String)
		{
			super();

			_url = host;

			addEventListener(Event.COMPLETE, completeHandler);
			addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityHandler);
			addEventListener(ProgressEvent.PROGRESS, progressHandler);
			_request = new URLRequest(_url);
			_request.method = URLRequestMethod.POST;
		}

		public function send(message:BaseMessage):void
		{
			var data:ByteArray = new ByteArray();
			data.writeInt(message.body.length + 4);
			data.writeShort(message.type);
			trace("client request serverType value: " + message.type);
			data.writeBytes(message.body);
			//////////////////
			_request.data = data;
			super.load(_request);
		}

		protected function completeHandler(event:Event):void
		{
			var byteArray:ByteArray = new ByteArray();
			this.readBytes(byteArray);

			if(handler != null)
			{
				handler(byteArray);
			}
		}

		private function errorHandler(event:IOErrorEvent):void
		{
			Logger.error("IOErrorEvent错误：" + event.toString());
		}

		private function securityHandler(event:SecurityErrorEvent):void
		{
			Logger.error("SecurityErrorEvent错误：" + event.toString());
		}

		private function progressHandler(event:ProgressEvent):void
		{

		}
	}
}